package com.xlh.util;

import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置文件读取工具类
 *
 * @author cheer
 */
public class PropertiesUtil {

    // 当打开多个资源文件时，缓存资源文件
    private static ConcurrentHashMap<String, PropertiesUtil> configMap = new ConcurrentHashMap<>();
    // 默认资源文件名称
    private static final String NAME = "config";

    // 资源文件
    private ResourceBundle resourceBundle = null;

    private PropertiesUtil(String name) {
        this.resourceBundle = ResourceBundle.getBundle(name);
    }

    public static PropertiesUtil getInstance() {
        return getInstance(NAME);
    }

    public static PropertiesUtil getInstance(String name) {
        configMap.putIfAbsent(name, new PropertiesUtil(name));
        return configMap.get(name);
    }

    /**
     * 根据key读取value
     *
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return resourceBundle.getString(key);
        } catch (MissingResourceException e) {
            return "";
        }
    }

    /**
     * 根据key读取value(整型)
     *
     * @param key
     * @return
     */
    public Integer getInt(String key) {
        try {
            String value = resourceBundle.getString(key);
            return Integer.parseInt(value);
        } catch (MissingResourceException e) {
            return null;
        }
    }

    /**
     * 根据key读取value(布尔)
     *
     * @param key
     * @return
     */
    public boolean getBool(String key) {
        try {
            String value = resourceBundle.getString(key);
            return "true".equals(value);
        } catch (MissingResourceException e) {
            return false;
        }
    }
}
